/* File Name : PagerWidget.js
 * Description: Composant de pagination pour les listes d'items
 */

import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import { getOpt } from '../tools.js';

const PagerWidget = Mn.View.extend({
    template: require('./templates/PagerWidget.mustache'),
    tagName: "div",
    className: "pager display_selector",
    regions: {},
    ui: {
        btn_cipp: 'a.btn[data-action=change_items_per_page]',
        btn_sp: 'a.btn[data-action=show_page]',
        sel_bottom: '#items_per_page_bottom',
        sel_top: '#items_per_page_top'
    },
    events: {
        'click @ui.btn_cipp': 'onButtonChangeItemsPerPageClicked',
        'click @ui.btn_sp': 'onButtonShowPageClicked',
        'change @ui.sel_bottom': 'onSelectChanged',
        'change @ui.sel_top': 'onSelectChanged'
    },
    triggers: {
        'navigate:page': 'navigate:page'
    },
    initialize() {
      this.position = getOpt(this, 'position', '');
    },
    onButtonChangeItemsPerPageClicked(event) {
        let selectid = $(event.currentTarget).data('selectid');
        let items_per_page = Number($('#'+selectid)[0].value);
        this.triggerMethod('navigate:itemsperpage', items_per_page);
    },
    onButtonShowPageClicked(event) {
        let page = $(event.currentTarget).data('page');
        this.triggerMethod('navigate:page', page-1);
    },
    onSelectChanged(event) {
        let selects = $('.pager select');
        for(let i = 0; i < selects.length ; i++) {
          selects[i].value = event.currentTarget.value;
        }
    },
    pagerElements() {
        // Retourne une liste d'items décrivant chaque composant du Pager
        // à afficher pour le template .mustache
        const currentPageScope = 2; // Nombre de boutons affichés de chaque côté de la page courante
        let currentPage = this.collection.state.currentPage + 1;
        let totalPages = this.collection.state.totalPages;
        let items = [];
        if(totalPages > 1) {
            for(let p = 1; p <= totalPages; p++) {
                let isCurrentPage = (p == currentPage);
                let isEllipsis = (1 < p) && (p < totalPages) && (Math.abs(currentPage - p) > currentPageScope);
                let isButton = (! isCurrentPage) && (! isEllipsis);
                if(! (isEllipsis && items[items.length-1]["isEllipsis"]) ) { // On concatène les ellipses
                    items.push({
                        isButton: isButton,
                        isCurrentPage: isCurrentPage,
                        isEllipsis: isEllipsis,
                        page: isEllipsis ? false : p
                    });
                }
            }
        }
        return items;
    },
    selectOptions() {
        // Retourne une liste d'items décrivant chaque option pour le
        // sélecteur de nombre d'items par page dans le .mustache
        const valueForAll = 1000000;
        let pageSizes = [ 10, 20, 30, 40, 50, valueForAll ];
        let items = [];
        for(let i = 0 ; i < pageSizes.length ; i++) {
            items.push({
                label: (pageSizes[i] == valueForAll) ? 'Tous' : pageSizes[i] + ' par page',
                selected: (pageSizes[i] == this.collection.state.pageSize) ? ' selected="selected"' : '',
                value: pageSizes[i]
            });
        }
        return items;
    },
    templateContext() {
        let currentPage = this.collection.state.currentPage + 1;
        let position = ['bottom', 'top'].includes(this.position) ? '_' + this.position : '';
        let context = {
            nextPage: this.collection.hasNextPage() ? currentPage + 1 : false,
            pagerElements: this.pagerElements(),
            position: position,
            previousPage: this.collection.hasPreviousPage() ? currentPage - 1 : false,
            selectOptions: this.selectOptions(),
            totalPagesLabel: this.collection.state.totalPages + ' page' + ((this.collection.state.totalPages > 1) ? 's' : ''),
            totalRecords: this.collection.state.totalRecords
        };
        return context;
    }
});
export default PagerWidget;
